/**
 * @(#)RabbitMQConstans.java, 2018/12/17
 * <p/>
 * Copyright 2018 Netease, Inc. All rights reserved.
 * NETEASE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.chengzhi.mq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author 阮承志(wb.ruanchengzhi @ mesg.corp.netease.com)
 **/
public interface RabbitMQConstants {
    static ConnectionFactory getconnectionFactory() {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.173.145");
        factory.setUsername("test");
        factory.setPassword("test");
        factory.setVirtualHost("mine");
        factory.setPort(5672);
        return factory;
    }

    static Connection getConnection() {
        ConnectionFactory factory = RabbitMQConstants.getconnectionFactory();
        Connection connection = null;
        try {
            connection = factory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return connection;
    }


    static Consumer getconsumer(Channel channel) {
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println("Consumer Received '" + message + "'");
            }
        };
        return consumer;
    }

    static void createExchangeAndQueue(Channel channel, boolean durable, String queueName) throws IOException {
        channel.exchangeDeclare("topic-exchange", BuiltinExchangeType.TOPIC, durable);
        Map<String, Object> param = new HashMap<>();
        param.put("x-message-ttl", 6000);
        param.put("x-dead-letter-exchange", "topic-exchange-dead");
        param.put("x-dead-letter-routing-key", "topicKey1-dead");
        channel.queueDeclare(queueName, true, false, false, param);
    }
}
